﻿using RedisHelper.User;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using DBModels;
using System.Threading.Tasks;

namespace Method.DAL
{
    /// <summary>
    /// 获取用户头像与用户昵称
    /// </summary>
    public class GetUserInfo
    {
        /// <summary>
        /// 获取用户头像与昵称
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <param name="avatar">返回用户头像</param>
        /// <param name="nickName">返回用户昵称</param>
        /// <returns>返回true表示获取到了,返回false表示查无此人</returns>
        public bool GetAvatarAndNickNameByUserId(int uid, ref string avatar, ref string nickName)
        {
            avatar = null;
            nickName = null;

            //从Redis查
            var infoR = new RedisHelper.User.UserInfo().GetUserInfo(uid);
            if (infoR is null)
            {
                //Redis中没有, 从数据库查
                using (ArticeContext context = new ArticeContext())
                {
                    var infoDB = context.UserInfos.FirstOrDefault(u => u.Id == uid);
                    if (infoDB is null)
                    {
                        //查无此人, 返回失败
                        return false;
                    }
                    else
                    {
                        avatar = infoDB.Avatar;
                        nickName = infoDB.NickName;
                        #region 保存到Reids中(可异步优化)
                        new RedisHelper.User.UserInfo().InsertUserInfo(uid, new Models.RModels.R_UserInfo()
                        {
                            Avatar = infoDB.Avatar,
                            NickName = infoDB.NickName,
                            Level = context.Accounts.FirstOrDefault(u => u.Id == uid).Level
                        });
                        #endregion
                        return true;
                    }

                }
            }
            else
            {
                avatar = infoR.Avatar;
                nickName = infoR.NickName;
                return true;
            }
        }
    }
}
